﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Nancy;
using Nancy.Bootstrapper;
using Nancy.Conventions;
using Nancy.TinyIoc;
using System.Reflection;

namespace FutianCloudAPIService.Nancy
{
    public class CloudBootstrapper: DefaultNancyBootstrapper
    {
        public CloudBootstrapper():base()
        {
        }


        protected override void ConfigureConventions(NancyConventions nancyConventions)
        {
            base.ConfigureConventions(nancyConventions);

            nancyConventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("JsPlugins", @"JsPlugins"));
        }

        protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
        {
            base.ApplicationStartup(container, pipelines);
            StaticConfiguration.DisableErrorTraces = false;

            StaticConfiguration.EnableRequestTracing = true;
        }

        protected override void RequestStartup(TinyIoCContainer requestContainer, IPipelines pipelines, NancyContext context)
        {
            base.RequestStartup(requestContainer, pipelines, context);

            //CORS Enable
            pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) =>
            {
                ctx.Response.WithHeader("Access-Control-Allow-Origin", "*")
                                .WithHeader("Access-Control-Allow-Methods", "POST,GET")
                                .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type");
            });
        }

        protected override byte[] FavIcon
        {
            get
            {
                 return this._favicon ?? (this._favicon = LoadFavIcon());
            }
        }

        private byte[] _favicon;

        private byte[] LoadFavIcon()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = "FutianCloudAPIService.fav.ico";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (MemoryStream mem = new MemoryStream())
            {
                stream.CopyTo(mem);

                return mem.ToArray();
            }
        }
    }
}
